package com.jaks.xpense;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;

import android.app.ListActivity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jaks.xpense.data.XpenseDatabase;
import com.jaks.xpense.utils.Globals;

public class RestoreDatabaseActivity extends ListActivity implements OnClickListener {

	private int position;
	private ArrayList<String> databases;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.restoredb);

		TextView restore = (TextView) findViewById(R.id.restoreDb);
		restore.setOnClickListener(this);

		position = -1;
		databases = new ArrayList<String>();
	}

	private void populate() {

		File sdPath = new File(Environment.getExternalStorageDirectory(), Globals.ExternalFolderName);
		if (sdPath.exists()) {

			FileFilter filter = new FileFilter() {

				@Override
				public boolean accept(File pathname) {
					return pathname.getName().endsWith(".db");
				}
			};

			File[] files = sdPath.listFiles(filter);
			for (File file : files) {
				databases.add(file.getName());
			}
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
		    android.R.layout.simple_list_item_single_choice, databases);
		setListAdapter(adapter);
	}

	private boolean restoreDatabase(String dbName) {
		File sd = Environment.getExternalStorageDirectory();
		File sdPath = new File(sd, Globals.ExternalFolderName);
		File sourceDbName = new File(sdPath.getAbsolutePath(), dbName);

		if (!sourceDbName.exists()) {
			Toast.makeText(this, "Source database not exists !", Toast.LENGTH_SHORT).show();
			return false;
		}

		XpenseDatabase db = new XpenseDatabase(this);
		try {
			db.restoreDatabase(sourceDbName.getAbsolutePath());
		} catch (IOException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			return false;
		}

		Toast.makeText(this, "Database restored !", Toast.LENGTH_LONG).show();
		return true;
	}

	@Override
	protected void onStart() {
		super.onStart();
		populate();
	}

	@Override
	public void onClick(View v) {

		if (position >= 0) {
			if (restoreDatabase(databases.get(position))) {
				setResult(RESULT_OK);
				finish();
			}
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		this.position = position;
	}
}
